import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueDevTools from 'vite-plugin-vue-devtools'
import fs from 'fs'
import path from 'path'

// 自动检测mkcert证书文件
function getHttpsConfig() {
  console.log('🔍 正在搜索HTTPS证书文件...');
  
  // 可能的证书文件名模式
  const possibleCertFiles = [
    'localhost+7.pem',
    'localhost+6.pem',
    'localhost+5.pem',
    'localhost+4.pem',
    'localhost+3.pem', 
    'localhost+2.pem',
    'localhost+1.pem',
    'localhost.pem'
  ];
  
  const possibleKeyFiles = [
    'localhost+7-key.pem',
    'localhost+6-key.pem',
    'localhost+5-key.pem',
    'localhost+4-key.pem',
    'localhost+3-key.pem',
    'localhost+2-key.pem', 
    'localhost+1-key.pem',
    'localhost-key.pem'
  ];
  
  let certFile = null;
  let keyFile = null;
  
  // 查找证书文件
  for (const cert of possibleCertFiles) {
    if (fs.existsSync(path.resolve(process.cwd(), cert))) {
      certFile = cert;
      console.log(`✅ 找到证书文件: ${cert}`);
      break;
    }
  }
  
  // 查找密钥文件
  for (const key of possibleKeyFiles) {
    if (fs.existsSync(path.resolve(process.cwd(), key))) {
      keyFile = key;
      console.log(`✅ 找到密钥文件: ${key}`);
      break;
    }
  }
  
  // 如果没有找到预期的文件，搜索所有.pem文件
  if (!certFile || !keyFile) {
    console.log('🔍 搜索所有.pem文件...');
    try {
      const files = fs.readdirSync(process.cwd());
      const pemFiles = files.filter(f => f.endsWith('.pem'));
      
      if (pemFiles.length >= 2) {
        console.log('📁 找到的.pem文件:', pemFiles);
        
        // 尝试自动匹配证书和密钥
        const certFiles = pemFiles.filter(f => !f.includes('-key'));
        const keyFiles = pemFiles.filter(f => f.includes('-key'));
        
        if (certFiles.length > 0 && keyFiles.length > 0) {
          certFile = certFiles[0];
          keyFile = keyFiles[0];
          console.log(`🔄 自动选择: 证书=${certFile}, 密钥=${keyFile}`);
        }
      }
    } catch (error) {
      console.log('⚠️ 无法读取目录文件列表');
    }
  }
  
  if (certFile && keyFile) {
    try {
      const httpsConfig = {
        key: fs.readFileSync(path.resolve(process.cwd(), keyFile)),
        cert: fs.readFileSync(path.resolve(process.cwd(), certFile)),
      };
      
      console.log('🎉 HTTPS配置成功！');
      console.log('🔒 将使用HTTPS协议启动服务器');
      
      return httpsConfig;
    } catch (error) {
      console.error('❌ 读取证书文件失败:', error.message);
      return false;
    }
  }
  
  console.log('⚠️ 未找到有效的HTTPS证书');
  console.log('💡 请运行 npm run cert 生成证书');
  console.log('🌐 将使用HTTP协议启动（VR功能可能受限）');
  
  return false;
}

// https://vite.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    vueDevTools(),
  ],
  server: {
    port: 3034,
    host: '0.0.0.0', // 允许所有IP访问
    https: getHttpsConfig(),
    cors: true, // 启用CORS
    // 开发服务器配置
    hmr: {
      port: 3035, // HMR端口
      host: 'localhost'
    },
    // 允许从任何来源访问
    headers: {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
      'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept, Authorization, Cache-Control'
    }
  },
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    },
  },
  // 生产构建优化
  build: {
    target: 'es2015',
    outDir: 'dist',
    assetsDir: 'assets',
    sourcemap: true,
    // VR应用需要的优化
    rollupOptions: {
      output: {
        manualChunks: {
          'three': ['three'],
          'three-mesh-ui': ['three-mesh-ui'],
          'vue': ['vue']
        }
      }
    }
  },
  // 预览服务器配置（用于生产构建预览）
  preview: {
    port: 3034,
    host: '0.0.0.0',
    https: getHttpsConfig(),
    cors: true
  }
})
